<template>
  <div ref="monacoEditorRef" :style="monacoEditorStyle"></div>
</template>

<script>
import { useMonacoEditor } from './useMonacoEditor.js';
import { onMounted, computed, watch } from 'vue';

export default {
  props: {
    width: {
      type: [String, Number],
      default: '100%',
    },
    height: {
      type: [String, Number],
      default: '400',
    },
    language: {
      type: String,
      default: 'javascript',
    },
    editorOption: {
      type: Object,
      default: () => ({}),
    },
    modelValue: {
      type: String,
      required: true,
    },
  },

  emits: ['blue', 'update:modelValue'],

  setup(props, { emit }) {
    const monacoEditorStyle = computed(() => {
      return {
        width: typeof props.width === 'string' ? props.width : props.width + 'px',
        height: typeof props.height === 'string' ? props.height : props.height + 'px',
      };
    });

    const { monacoEditorRef, createEditor, updateVal, updateOptions, getEditor } = useMonacoEditor(props.language);

    onMounted(() => {
      const monacoEditor = createEditor(props.editorOption);
      updateMonacoVal(props.modelValue);
      monacoEditor?.onDidChangeModelContent(() => {
        emit('update:modelValue', monacoEditor.getValue());
      });
      monacoEditor?.onDidBlurEditorText(() => {
        emit('blue');
      });
    });

    watch(
      () => props.modelValue,
      () => {
        updateMonacoVal(props.modelValue);
      },
    );

    function updateMonacoVal(val) {
      if (val !== getEditor()?.getValue()) {
        updateVal(val);
      }
    }

    return {
      monacoEditorRef,
      monacoEditorStyle,
      updateOptions,
    };
  },
};
</script>
